package com.xiguaji.tiktok.config.interceptor;

import com.xiguaji.boot.toolkit.HttpUtil;
import com.xiguaji.tiktok.utils.CheckMobile;
import com.xiguaji.tiktok.v1.tiktok.permission.repository.UserRoleRepository;
import com.xiguaji.tiktok.v1.tiktok.sys.model.SysMenu;
import com.xiguaji.tiktok.v1.tiktok.sys.model.SysUserVisitRecord;
import com.xiguaji.tiktok.v1.tiktok.sys.repository.SysMenuRepository;
import com.xiguaji.tiktok.v1.tiktok.sys.repository.SysUserVisitRecordRepository;
import com.xiguaji.tiktok.v1.user.model.User;
import com.xiguaji.tiktok.v1.user.service.UserService;
import com.xiguaji.tiktok.v1.user.validate.UserHandler;
import nl.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
public class UserVisitInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;

    @Autowired
    UserHandler userHandler;

    @Autowired
    UserRoleRepository userRoleRepository;

    @Autowired
    SysMenuRepository sysMenuRepository;

    @Autowired
    SysUserVisitRecordRepository sysUserVisitRecordRepository;

    ThreadLocal<SysUserVisitRecord> visitRecord = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        SysMenu sysMenu = getSysMenu(request,handler);
        // 是否需要记录
        if(null != sysMenu){
            SysUserVisitRecord sysUserVisitRecord = new SysUserVisitRecord();
            sysUserVisitRecord.setRequestUrl(request.getRequestURL().toString());
            sysUserVisitRecord.setMenuId(sysMenu.getId());
            sysUserVisitRecord.setCreateTime(System.currentTimeMillis()/1000);
            sysUserVisitRecord.setDateCode(Integer.parseInt(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"))));
            sysUserVisitRecord.setRequestIp(HttpUtil.getIp());
            sysUserVisitRecord.setMobile(CheckMobile.check());
            sysUserVisitRecord.setRequestMethod(request.getMethod());
            //转成UserAgent对象
            UserAgent userAgent = UserAgent.parseUserAgentString(HttpUtil.getRequest().getHeader("User-Agent"));
            sysUserVisitRecord.setBrowser(userAgent.getBrowser().getName());
            sysUserVisitRecord.setOs(userAgent.getOperatingSystem().getName());
            User user = userHandler.getUser();
            if(null == user){
                sysUserVisitRecord.setUserId(0l);
                sysUserVisitRecord.setVersionId(0l);
                sysUserVisitRecord.setUserKey(sysUserVisitRecord.getRequestIp());
            }else {
                sysUserVisitRecord.setUserId(user.getId());
                sysUserVisitRecord.setVersionId(userHandler.getRoleId());
                sysUserVisitRecord.setUserKey(String.valueOf(user.getId()));
            }
            sysUserVisitRecordRepository.save(sysUserVisitRecord);
            visitRecord.set(sysUserVisitRecord);
        }

        // 清除无效的Token
        userHandler.clearCookieByToken();

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) {
        SysUserVisitRecord sysUserVisitRecord = visitRecord.get();

        if(null != sysUserVisitRecord){
            if(null != modelAndView){
                sysUserVisitRecord.setRequestCode(String.valueOf(response.getStatus()));
                List<SysMenu> childMenus = sysMenuRepository.findByParentId(sysUserVisitRecord.getMenuId());
                modelAndView.addObject("recordList",childMenus);
                childMenus.forEach(c ->System.out.println(c.toString()));
                sysUserVisitRecord.setRequestMsg("OK");
            }
        }

    }
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex) {

        SysUserVisitRecord sysUserVisitRecord = visitRecord.get();

        if(null != sysUserVisitRecord){
            // 针对登入过的用户重新再获取一次用户信息
            User user = userHandler.getUser();

            if(null != user){
                sysUserVisitRecord.setUserId(user.getId());
                sysUserVisitRecord.setVersionId(userHandler.getRoleId());
                sysUserVisitRecord.setUserKey(String.valueOf(user.getId()));
            }
            sysUserVisitRecordRepository.save(sysUserVisitRecord);
            visitRecord.remove();
        }
    }

    private SysMenu getSysMenu(HttpServletRequest request, Object handler){
        SysMenu sysMenu = sysMenuRepository.findByUrl(request.getRequestURI());
        // 多个URL归属到同一个统计
        if(null == sysMenu){
            sysMenu = sysMenuRepository.findByUrlLike("%"+request.getRequestURI()+"%");
            // restful风格参数
            if(null == sysMenu){
                try{
                    String [] uri = ((HandlerMethod)handler).getMethodAnnotation(RequestMapping.class).value();

                    if(null != uri && uri.length > 0){
                        sysMenu = sysMenuRepository.findByUrl(uri[0]);
                    }
                }catch (ClassCastException e){
                    return null;
                }
            }
        }
        return sysMenu;
    }
}
